package TCP.TCP2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket listenSocket = null;
    //绑定服务器端口号
    public TcpEchoServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        //线程池解决一个连接处理多个请求
        ExecutorService server = Executors.newCachedThreadPool();
        while(true) {
            //接受连接，没有连接就会阻塞等待
            Socket clientSocket = listenSocket.accept();
            server.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %s] 客户端上线~\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //TCP特点：字节流
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while(true) {
                //1.接收并解析请求
                Scanner input = new Scanner(inputStream);
                //检查客户端是否下线
                if(!input.hasNext()) {
                    System.out.printf("[%s : %s] 客户端下线~\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                String request = input.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.将响应发送给客户端
                PrintWriter output = new PrintWriter(outputStream);
                output.println(response);
                //刷新缓冲区
                output.flush();
                //4.打印日志
                System.out.printf("[%s : %s] req: %s; resp: %s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //防止文件描述符占满
            clientSocket.close();
        }
    }
    //这是一个回显服务器
    private String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
